package com.rexense.beacon.service;

import com.rexense.beacon.entity.Label;
import com.rexense.beacon.entity.Location;
import org.redisson.api.RPriorityQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class LabelService {

    @Autowired
    private RedissonClient redisson;

    private final static String LABEL_PREFIX = "LABEL:";

    public void setLabelLocation(String labelId, String msgId, Location location) {
        RPriorityQueue<Label> priorityQueue = redisson.getPriorityQueue(LABEL_PREFIX + labelId);
        priorityQueue.add(
                Label.builder()
                        .labelId(labelId).lastUpdate(System.currentTimeMillis())
                        .updateMsgId(msgId)
                        .x(location.getX())
                        .y(location.getY())
                        .build().init()
        );
        priorityQueue.expire(5, TimeUnit.HOURS);
    }

    public Label getLabelById(String labelId) {
        RPriorityQueue<Label> priorityQueue = redisson.getPriorityQueue(LABEL_PREFIX + labelId);
        return priorityQueue.peek();
    }

    public List<Label> listLabelLocation(String labelId) {
        RPriorityQueue<Label> priorityQueue = redisson.getPriorityQueue(LABEL_PREFIX + labelId);
        if (priorityQueue != null) {

            ArrayList<Label> labels = new ArrayList<>(priorityQueue.readAll());
            return labels.stream().distinct().sorted().collect(Collectors.toList());
        }

        return new ArrayList<>(0);
    }

}
